package net.luohuasheng.bee.proxy.mybatis.executor.processor;

import net.luohuasheng.bee.proxy.core.utils.jpa.dto.JpaColumnDto;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.session.Configuration;

import java.util.List;

/**
 * @author luohuasheng
 */
public class UpdateEntityByIdProcessor extends BaseProcessor {

    public UpdateEntityByIdProcessor(Configuration configuration, Class<?> entityClass) {
        super(configuration, entityClass);
    }

    @Override
    public void rewrite(Invocation invocation, MappedStatement ms, BoundSql boundSql, Object parameter) {

    }

    @Override
    public SqlSource createSqlSource() {
        StringBuilder colStr = new StringBuilder();
        for (JpaColumnDto column : jpaTableDto.getColumns()) {
            if (!column.isPk() && column.isUpdatable()) {
                colStr.append("<if test=\"").append(column.getField().getName()).append(" != null\">").append(column.getName()).append(" = #{").append(column.getField().getName()).append("},").append("</if>");
            }
        }
        return createSqlSource("UPDATE " + jpaTableDto.getName() + " <set> " + colStr.toString() + " </set> " + addLogicConditions(jpaTableDto.getColumns()) + createPkSql(jpaTableDto.getColumns()));
    }

    @Override
    protected String createPkSql(List<JpaColumnDto> columns) {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (JpaColumnDto column : columns) {
            if (column.isPk()) {
                sb.append(" and ").append(column.getName()).append(" = #{").append(column.getField().getName()).append("}");
                i++;
            }
        }
        return sb.toString();
    }
}
